package com.example.docking.httpCRM.httpSend;

import com.example.docking.httpCRM.OrderReadRetData;
import com.example.docking.httpCRM.dao.*;
import com.example.docking.httpCRM.util.CRM_MD5;
import com.example.docking.httpCRM.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class XToolsCRMOrderAPI {
    private static final OkHttpClient client = new OkHttpClient();
    private static final Gson gson = new Gson();
    private static final Map<String, String> cache = new HashMap<>();


    // 获取sid，如果缓存中没有则进行登录获取
    public static String getSid(String cmd, String appid, String comkeyid, String com, String part) throws IOException {
        String sid = cache.get("sid");
        if (sid == null) {
            XToolsCRMLoginAPI loginAPI = new XToolsCRMLoginAPI();
            GenericResponse<LoginRetData> response = loginAPI.login(cmd, appid, Constants.APPKEY, comkeyid, com, part);
            if (response != null && response.getOk() == 1) {
                sid = response.getRet().getSid();
                cache.put("sid", sid);
            }
        }
        return sid;
    }

    // 订单读取接口方法
    public static GenericResponse<OrderReadRetData> readOrderInfo(String cmd, String appid, OrderReadParam param) throws IOException {
        String stamp = String.valueOf(System.currentTimeMillis() / 1000);
        String sid = getSid(cmd, appid, "", "", ""); // 这里的comkeyid, com, part 可根据实际情况调整
        LoginInfo upr = new LoginInfo(sid);

        // 生成参数 md
        String mdInput = gson.toJson(param) + stamp + gson.toJson(upr) + cmd + Constants.APPKEY;
        CRM_MD5 md5 = new CRM_MD5();
        String md = md5.generateMD5(mdInput);

        RequestBodyParam requestBodyParam = new RequestBodyParam<OrderReadParam>(cmd, appid, stamp, upr, md);
        requestBodyParam.setParam(param);
        String json = gson.toJson(requestBodyParam);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(Constants.ORDER_API_URL)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseBodyString = Objects.requireNonNull(response.body()).string();
            GenericResponse<OrderReadRetData> responseObject = gson.fromJson(responseBodyString, new TypeToken<GenericResponse<OrderReadRetData>>() {
            }.getType());
            return responseObject;
        }
    }

    public static void main(String[] args) {
        String cmd = Constants.CMD_OUTPUT;
        String appid = Constants.APPID;
        OrderReadParam param = new OrderReadParam(Constants.DT_CONTRACT, 0, 0, null); // 这里extend为null，代表基本调用

        try {
            GenericResponse<OrderReadRetData> response = readOrderInfo(cmd, appid, param);
            if (response.getOk() == 1) {
                OrderReadRetData retData = response.getRet();
                if (retData.getOk() == 1) {
                    System.out.println("订单信息读取成功，数据: " + retData.getData());
                } else {
                    System.out.println("订单信息读取失败");
                }
            } else {
                System.out.println("登录接口调用失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

